package cn.vc.communityservice.controller;

import cn.vc.basicmodule.entity.Result;
import cn.vc.communityservice.service.CommunityAttentionService;
import cn.vc.feign.userclient.entity.User;
import com.alibaba.fastjson.JSON;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

@RestController
@RequestMapping("/community_attention")
public class CommunityAttentionController {
    private final CommunityAttentionService communityAttentionService;
    private final RedisTemplate redisTemplate;
    private final HttpServletRequest request;

    public CommunityAttentionController(CommunityAttentionService communityAttentionService, RedisTemplate redisTemplate, HttpServletRequest request) {
        this.communityAttentionService = communityAttentionService;
        this.redisTemplate = redisTemplate;
        this.request = request;
    }



    /**
     * <h2>关注社区</h2>
     * @param communityId 要关注的社区ID
     * @return
     */
    @PostMapping
    public Result<?> attention(@RequestParam("communityId") Long communityId) {
        User myUser = redisTemplate.opsForValue().get(request.getHeader("token"))!=null? JSON.parseObject(redisTemplate.opsForValue().get(request.getHeader("token")).toString(), User.class):null;
        if (myUser==null) return new Result<>(0);
        boolean bo = communityAttentionService.attention(communityId, myUser.getId());
        return new Result<>(bo);
    }



    /**
     * <h2>取关社区</h2>
     * @param id 需要删除的关系表ID
     * @return
     */
    @DeleteMapping
    public Result<?> noAttention(@RequestParam("id") Long id) {
        User myUser = redisTemplate.opsForValue().get(request.getHeader("token"))!=null? JSON.parseObject(redisTemplate.opsForValue().get(request.getHeader("token")).toString(), User.class):null;
        if (myUser==null) return new Result<>(0);
        boolean bo = communityAttentionService.deleteById(id);
        return new Result<>(bo);
    }
}
